package com.wtgroup.demo.mianshi.线程;

import lombok.SneakyThrows;
import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author dafei
 * @version 0.1
 * @date 2021/4/22 21:40
 */
public class D_ThreadLocal {
    // ThreadLocal 含义理解: 线程本地变量
    @Test
    public void demo() {
        ThreadLocal localVar1 = new ThreadLocal();
        localVar1.set("A");
        System.out.println(localVar1.get());
        localVar1.set("B");
        System.out.println(localVar1.get());
        localVar1.remove();
        System.out.println(localVar1.get());
    }

    public void demo2() {
        // 体会 ThreadLocal 和 AtomicInteger API
        ThreadLocal localVar = new ThreadLocal();
        localVar.set(1);
        localVar.get();

        ThreadLocal localVar2 = new ThreadLocal();
        localVar2.set(2); // key localVar2 -> 2
        localVar.get();

        AtomicInteger ai = new AtomicInteger();
        ai.set(1);
        ai.get();
    }

    @Test
    public void foo1() {
        ThreadLocal localVar1 = new ThreadLocal();
        // ThreadLocal localVar1 = new InheritableThreadLocal(); // 用它会发生什么呢?
        localVar1.set(898);
        System.out.println("main get localVar1 = " + localVar1.get()); // 898

        Thread t= new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("other thread get localVar1 = " + localVar1.get()); // null
            }
        });

        localVar1.set("改了哦");
        t.start();
        System.out.println("main 再次get : " + localVar1.get());



        /**
         * main get localVar1 = 898
         * main get localVar1 = null // InheritableThreadLocal 时, 能够读到
         */

    }

    // 内存泄露????

    @Test
    public void foo2() {
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        executorService.submit(() -> {

            for (int i = 0; i < 1_0000; i++) {

            }


        });
    }





}
